//
//  RequestLoggerPlugin.swift
//  SwiftBaseProject
//
//  Created by 苏州巨细 on 2018/5/23.
//  Copyright © 2018年 苏州巨细. All rights reserved.
//

import Foundation
import Moya
import SwiftyJSON

final class RequestLoggerPlugin: PluginType {
    
    /// 是否显示请求信息
    private let showRequestInfo: Bool
    
    /// 是否显示返回信息
    private let showResponseInfo: Bool

    init(request: Bool = true, response: Bool = true) {
        self.showRequestInfo = request
        self.showResponseInfo = response
    }
   
    public func willSend(_ request: RequestType, target: TargetType) {
        if !showRequestInfo {
            return
        }
        print(
            """
            ------ start ------
            请求地址:\(target.baseURL)\(target.path)
            请求参数:\(JSON(request.request?.httpBody as Any))
            ------ end --------
            
            """)
    }
    
    /// Called by the provider as soon as a response arrives, even if the request is canceled.
    public func didReceive(_ result: Result<Moya.Response, MoyaError>, target: TargetType) {
        if !self.showResponseInfo {
            return
        }
        
        if case .success(let response) = result {
            let json = JSON(response.data)
            guard let url = response.request?.url else {
                return
            }
            if response.statusCode == 200 {
                print(
                    """
                    ------ start ------
                    请求地址：\(url)
                    接口状态码：\(response.statusCode)
                    返回参数：\(json)
                    ------ end --------
                    
                    """
                )
            }else{
                print(
                    """
                    ------ start ------
                    请求地址：\(url)
                    接口状态码：\(response.statusCode)
                    ------ end --------
                    
                    """
                )
            }
        } else {
            
        }
        
    }
}
